package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import define.Constants;

/**
 * Get data, include all files, from the server
 * 
 * @author Alex Tran
 * 
 */
public class GetDataFromServerAsync extends AsyncTask<String, Void, Integer> {

	public static int number_of_files = 0;

	@Override
	protected Integer doInBackground(String... params) {
		return getData();
	}

	private int getData() {
		try {
			HttpClient mHttpClient = new DefaultHttpClient();
			HttpGet mHttpRequest = new HttpGet("http://" + Constants.IP
					+ "/cgi-bin/photo");
			HttpResponse mHttpResponse = mHttpClient.execute(mHttpRequest);

			InputStream mIs = mHttpResponse.getEntity().getContent();
			BufferedReader mBr = new BufferedReader(new InputStreamReader(mIs));

			String LINE = null;
			while ((LINE = mBr.readLine()) != null) {
				if (LINE.indexOf("thumbNail?fn=") != -1
						&& LINE.indexOf("border") != -1) {
					number_of_files++;
				}
			}
			mIs.close();

			return number_of_files;
		} catch (MalformedURLException e) {
			return 0;
		} catch (IOException e) {
			return 0;
		}
	}
}
